package com.uduemc.security.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {

	private static String pathname = "D:\\sts-workspace\\uduemc-security\\uduemc-security-demo\\src\\main\\resources\\upload";

	@PostMapping("/upload")
	public String upload(MultipartFile file) throws Exception {
		// 提交的form data 名称
		System.out.println(file.getName());
		// 原始文件名称
		System.out.println(file.getOriginalFilename());
		// 文件大小
		System.out.println(file.getSize());

		// 将文件存储在指定的位置上
		File localFile = new File(pathname, new Date().getTime() + ".txt");
		file.transferTo(localFile);

		return localFile.getAbsolutePath();
	}

	@GetMapping("/download/{id}")
	public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		/**
		 * Java 1.7 以上版本支持下列语法 InputStream、OutputStream 会自动 close
		 */
		try (InputStream inputStream = new FileInputStream(new File(pathname, id + ".txt"));
				OutputStream outputStream = response.getOutputStream();) {

			// response header
			response.setContentType("application/x-download");
			// 下载文件中文乱码的问题
			response.addHeader("Content-Disposition", "attachment;filename=" + new String("下载文件.txt".getBytes("UTF-8"),"iso-8859-1"));

			IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
		}
	}

}
